import axios from 'axios'
import { ElMessage } from 'element-plus'
// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'

const createService = (baseUrl = '') => {
    // 创建 axios 实例
    const baseURL = baseUrl || import.meta.env.VITE_APP_BASE_API

    const service = axios.create({
        baseURL,
        timeout: 50000
    })

    // request拦截器（主要是携带上token）
    service.interceptors.request.use(config => {
        config.headers['key'] = 'headerValue'
        return config
    }, error => {
        console.log(error)
        return Promise.reject(error)
    })

    service.interceptors.response.use(response => {
        return response.data
    }, error => {
        console.log('err' + error)
        if (error.response) {
            const errorMessage = error.response.data === null ? '系统内部异常，请联系网站管理员' : error.response.data.message
            switch (error.response.status) {
                case 404:
                    ElMessage({
                        message: '很抱歉，资源未找到' || 'Error',
                        type: 'error',
                        duration: 5 * 1000
                    })
                    break
                case 403:
                    ElMessage({
                        message: '很抱歉，您暂无该操作权限' || 'Error',
                        type: 'error',
                        duration: 5 * 1000
                    })
                    break
                case 401:
                    ElMessage({
                        message: '很抱歉，认证已失效，请重新登录' || 'Error',
                        type: 'error',
                        duration: 5 * 1000
                    })
                    break
                default:
                    if (errorMessage) {
                        ElMessage({
                            message: errorMessage,
                            type: 'error',
                            duration: 5 * 1000
                        })
                    }
                    break
            }
        }
        return Promise.reject(error)
    })

    return service
}

const request = createService()

export { createService }
export default request